package com.newsee.remote.ecommerce.commerce.colipu.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newsee.remote.common.database.entity.CommerceColipuCategory;
import com.newsee.remote.common.database.mapper.CommerceColipuCategoryMapper;
import com.newsee.remote.common.dto.ecommerce.colipu.CategoryColDTO;
import com.newsee.remote.common.enumeration.DeleteFlagEnum;
import com.newsee.remote.common.utils.http.HttpClientExecutor;
import com.newsee.remote.common.utils.tools.CcUtils;
import com.newsee.remote.ecommerce.commerce.colipu.service.IColipuCategoryService;
import com.newsee.remote.ecommerce.commerce.colipu.service.IColipuSkuDetailService;
import com.newsee.remote.ecommerce.commerce.colipu.service.IColipuTokenService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 科力普服务实现类
 * </p>
 *
 * @author liangzhichen
 * @since 2019-07-16
 */
@Slf4j
@Service
public class ColipuCategoryServiceImpl extends ServiceImpl<CommerceColipuCategoryMapper, CommerceColipuCategory> implements IColipuCategoryService {

    /**
     * 统一url
     */
    @Value("${colipuContextPath}")
    private String colipuContextPath;

    /**
     * 获取商品分类方法名
     */
    @Value("${colipuGetCategoriesUrl}")
    private String colipuGetCategoriesUrl;

    private final IColipuTokenService iColipuTokenService;

    private final IColipuSkuDetailService icolipuskudetailservice;

    public ColipuCategoryServiceImpl(IColipuTokenService iColipuTokenService, IColipuSkuDetailService icolipuskudetailservice) {
        this.iColipuTokenService = iColipuTokenService;
        this.icolipuskudetailservice = icolipuskudetailservice;
    }

    @Override
    public void sync() {
        //1、获取token
        String token = iColipuTokenService.getToken();
        //2、获取分类
        List<CategoryColDTO> categorys = getCategory(token);
        List<String> categoryIds = CcUtils.collect(categorys, CategoryColDTO::getId);
        //3、插入中间表分类表
        addToCategory(categorys);
        //4、同步分类下的商品
        icolipuskudetailservice.sync(categoryIds);
    }


    /**
     * 插入中间表分类表
     *
     * @param categorys 全量的分类
     */
    private void addToCategory(List<CategoryColDTO> categorys) {
        //需要新增的分类
        List<CommerceColipuCategory> addList = new LinkedList<>();
        //需要修改的分类
        List<CommerceColipuCategory> updateList = new LinkedList<>();
        LocalDateTime now = LocalDateTime.now();

        List<CommerceColipuCategory> categorysExist = list(new QueryWrapper<>());
        if (CollectionUtils.isNotEmpty(categorysExist)) {
            //全量的分类to Map
            Map<String, CategoryColDTO> categoryMap = CcUtils.toMap(categorys, CategoryColDTO::getId);

            //判断已同步的分类是否需要修改
            categorysExist.forEach(categoryExist -> {
                String categoryId = categoryExist.getCategoryId();
                CategoryColDTO categoryColDTO = categoryMap.get(categoryId);
                if (null == categoryColDTO) {
                    //删除
                    categoryExist.setDeleteFlag(DeleteFlagEnum.IS_DELETE.getCode());
                    categoryExist.setUpdateTime(now);
                    updateList.add(categoryExist);
                } else {
                    //需要修改
                    if (!categoryColDTO.getName().equals(categoryExist.getCategoryName())) {
                        categoryExist.setUpdateTime(now);
                        categoryExist.setCategoryName(categoryColDTO.getName());
                        updateList.add(categoryExist);
                    }
                }

                //去除
                categorys.remove(categoryColDTO);
            });
        }

        //最后剩下的新增的
        categorys.forEach(category -> {
            CommerceColipuCategory colipuCategory = new CommerceColipuCategory();
            colipuCategory.setCategoryId(category.getId());
            colipuCategory.setCategoryName(category.getName());
            addList.add(colipuCategory);
        });

        if (CollectionUtils.isNotEmpty(addList)) {
            addList.forEach(this::save);
        }
        if (CollectionUtils.isNotEmpty(updateList)) {
            updateList.forEach(this::updateById);
        }
    }

    /**
     * 获取科力普分类接口
     *
     * @param token header中Token
     */
    private List<CategoryColDTO> getCategory(String token) {
        List<CategoryColDTO> list = new ArrayList<>();

        //获取京东分类url
        String url = colipuContextPath + colipuGetCategoriesUrl;
        Map<String, String> params = new HashMap<>(0);
        Map<String, String> headers = new HashMap<>(1);
        headers.put("Colipu-Token", token);
        try {
            String response = HttpClientExecutor.doGet(url, params, headers);
            JSONObject jsonReturn = JSON.parseObject(response);
            if (jsonReturn.getBoolean("success")) {
                String result = jsonReturn.getString("result");
                list = JSONObject.parseArray(result, CategoryColDTO.class);
            } else {
                log.error("error:requestId(" + jsonReturn.getString("requestId")
                        + ");errorcode(" + jsonReturn.getString("errorcode")
                        + ");errormsg(" + jsonReturn.getString("errormsg") + ")");
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return list;
    }


}
